package trans.main;

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import trans.tpmap.MapSplitter;
import util.gen.*;

/**
 * Prints out processed '.celp' files as '.sgr' files for import into Affy's IGB. 
 */
public class IntensityPrinter {
	
	//fields
	private File bpmapFile; 
	private File infoFile;
	private File[] intensityFiles; 
	
	public IntensityPrinter (String[] args){
		processArgs(args);
		
		//get .tpmap file info
		ArrayList info = (ArrayList)IO.fetchObject(infoFile);
		
		for (int j=0; j< intensityFiles.length; j++){
			
			//fetch float[] of normalized intensity values for treatment and control
			float[] intensities = (float[])IO.fetchObject(intensityFiles[j]);
			
			//break both apart by chromosome using the bpmapInfo ArrayList, save to disk, 
			//	might be able to get away with keeping em in memory?  Only need to run once.
			String uniqueIdT = MapSplitter.breakSaveIntensityValues(info, intensities,intensityFiles[j].toString());
			
			//for each chromosome, safe to parallel process on cluster
			int num = info.size();
			String chromosome;
			int[] positions;
			
			
			//make PrintWriter
			PrintWriter out=null;
			try {
				out = new PrintWriter(new FileWriter(intensityFiles[j]+".sgr"));
			}catch(IOException e){
				e.printStackTrace();
			}
			
			for (int i=1; i<num; i+=4){
				System.out.println("Printing Intensities...");
				
				//fetch windows to scan, the int[][] made in the WindowMaker
				chromosome = (String)info.get(i);
				System.out.println("\tTesting chromosome: "+chromosome);
				
				//fetch treatment and control normalized, transformed, and chromosome divided int[]'s
				intensities = (float[])IO.fetchObject(new File(intensityFiles[j]+chromosome+uniqueIdT));
				
				//fetch bp positions to use in converting window indexes to real base pairs
				positions = (int[])IO.fetchObject(new File(bpmapFile+chromosome));
				
				//run oligos
				int numberOligos = intensities.length;
				for (int k=0; k<numberOligos; k++){
					//print treatment
					out.println(chromosome+"\t"+positions[k]+"\t"+intensities[k]);
					
				}
			}	
			//close PrintWriters
			out.close();
			
			//delete .delMeTmp files
			IO.deleteFiles(intensityFiles[j].getParent(), uniqueIdT);
		}
		
	}
	
	/**This method will process each argument and assign any new varibles*/
	public void processArgs(String[] args){
		File directory = null;
		File intensityDir = null;
		Pattern pat = Pattern.compile("-[a-z]");
		for (int i = 0; i<args.length; i++){
			String lcArg = args[i].toLowerCase();
			Matcher mat = pat.matcher(lcArg);
			if (mat.matches()){
				char test = args[i].charAt(1);
				try{
					switch (test){
					case 'b': directory = new File(args[i+1]); i++; break;
					case 'i': intensityDir = new File(args[i+1]); i++; break;
					case 'h': printDocs(); System.exit(0);
					default: System.out.println("\nProblem, unknown option! " + mat.group());
					}
				}
				catch (Exception e){
					System.out.print("\nSorry, something doesn't look right with this parameter request: -"+test);
					System.out.println();
					System.exit(0);
				}
			}
		}
		//check to see if they entered required params
		if (directory==null || directory.isDirectory() == false){
			System.out.println("\nCannot find your tpmap directory!\n");
			System.exit(0);
		}
		if (intensityDir != null) intensityFiles = IO.extractFiles(intensityDir, "celp");
		else {
			System.out.println("\nCannot find your intensity files/ directory!\n");
			System.exit(0);
		}
		
		bpmapFile = new File(directory.toString(),"tpmap.fa"); 
		infoFile = new File(directory.toString(),"tpmap.faInfo");
		
	}
	
	public static void printDocs(){
		System.out.println("\n" +
				"**************************************************************************************\n" +
				"**                        Intensity Printer: April 2007                             **\n" +
				"**************************************************************************************\n" +
				"IP prints to file  intensity scores in a .sgr text format for direct import into\n" +
				"Affy's IGB.\n" +
				"\n" +
				"Use the following options when running IP:\n\n" +
				"-b Full path directory name for the 'xxxTPMapFiles' generated by the TPMapProcessor\n" +
				"-i The full path director or file name for the xxx.celp intensity files.\n" +
				
				"\n" +
				"Example: java -Xmx256M -jar pathTo/T2/Apps/IntensityPrinter -b /affy/TPMapFiles/ -i \n" +
				"      /affy/t.celp \n" +
				"\n" +
		"**************************************************************************************\n");
	}	
	public static void main(String[] args) {
		if (args.length <4){
			printDocs();
			System.exit(0);
		}
		new IntensityPrinter(args);
	}
	
}
